# -*- coding: utf-8 -*-

'''

@author: wyndem
@Emil:   wyndem.wen@timevary.com
@FileName: lol.py
@Time: 2018/7/21 13:16
@Description: 平台各个验证

'''
import datetime
import json
import os
import re
import threading
import time
import asyncio

import requests

import config
from mail import Mail163
from tool import TOOL as t, retry
import requests as r

'''
币卡的针对类
'''
class coinsuper():

    def __init__(self):
        #创建163邮箱
        self.m=Mail163('coinsuper','Welcome to',True)
        #获取代理
        self.proxies = {
            "https": t.getProXY()
        }
        header = t.getHeaders()
        header['Content - Type'] = "application/json;charset=UTF-8"
        header['X-B3-Traceid'] = "9084308976537210"
        header['XX-B3-Spanid'] = "9084308976537210"
        header['Host'] = "www.coinsuper.com"
        header['X-Requested-With'] = "XMLHttpRequest"
        header['Referer'] = "https://www.coinsuper.com/"
        header['Accept-Language'] = "zh-CN,zh;q=0.8"
        header['Accept'] = "*/*"
        self.header=header
        # 当前发送验证码的时间
        self.s_time =''

    '获取极验的key'
    @retry
    def getjiyan_key(self):
        jy = r.get('https://share.coinsuper.shop/v1/common/gt/startCaptcha?clientType=WEB', headers=t.getHeaders(),
                   proxies=self.proxies)
        data = jy.json().get('data')
        challenge = data.get('challenge')
        gt = data.get('gt')

        # 获取验证码
        jypamr = {
            'gt': str(gt),
            'challenge': str(challenge),
            'url': 'https://share.coinsuper.shop/',
        }
        return t.jiyanapi_s(True, jypamr)

    '币卡的滑动验证'
    def geetest_key(self,v,user):
        json_data = {
            "lang": "en-GB",
            "source": "WEB",
            "geetestChallenge": v[0],
            "geetestValidate": v[1],
            "geetestSeccode": v[1] + "|jordan",
            "clientType": "WEB",
            "userEmail": user,
            "operationType": "2"
        }

        i = 10
        while i:
            try:
                res = r.post('https://share.coinsuper.shop/v1/common/gt/validate', proxies=self.proxies,
                             data=json.dumps(json_data), headers=self.header)
                break
            except requests.exceptions.SSLError:
                self.proxies = t.getProXY()
                i -= 1
            except AttributeError:
                pass
        if res==None:
            return res
        geetest_code_key = res.json()
        print('极验成功！')
        return geetest_code_key.get('data').get('geetest_code_key')

    '发送验证码'
    def send_sms(self,user,geetest_code_key):
        s_time = int(time.time() * 1000)
        sign = t.md5Pass('accesskey=webAccessKey&email=%s&emailAuthType=RG&lang=en-GB&time=%s' % (user, str(s_time)))
        json_data = {
            "common": {
                "time": str(s_time),
                "lang": "en-GB",
                "sign": sign
            },
            "data": {
                "source": "WEB",
                "email":user,
                "emailAuthType": "RG",
                "geetestKey": geetest_code_key
            }
        }
        i=10
        while i:
            try:
                res = r.post('https://share.coinsuper.shop/v1/member/send/remail', data=json.dumps(json_data),
                             headers=self.header, proxies=self.proxies).json()
                if res != None and res.get('code') == '1000':
                    self.s_time = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
                    print(self.s_time)
                break
            except requests.exceptions.SSLError:
                self.proxies = t.getProXY()
                i-=1

        return  res

    '获取验证码'
    def login_mail(self,user,pwd,cont):
        while 1:
            if  self.m.login(user,pwd):
                for i in range(cont):
                    try:
                        print('尝试第%d次' % (i + 1))
                        time.sleep(i + 1)
                        mail_code = self.m.integrate_mail(self.s_time)
                        if mail_code != None:
                            mail_code = self.getvrif(mail_code[1], " code is")
                            return mail_code
                    except:
                        pass

    '使用ck获取验证码'
    def get_vrif(self,msg_mail,cont,s_time):
        self.m.cookies = msg_mail[0]
        self.m.mail_163_url = msg_mail[1]
        for i in range(cont):
            try:
                print('尝试第%d次' % (i + 1))
                time.sleep(i + 1)
                mail_code = self.m.integrate_mail(s_time)
                if mail_code != None:
                    mail_code = self.getvrif(mail_code[1], 'Your verification code is')
                    print(mail_code)
                    return mail_code
            except:
                pass
        return None




    '注册'
    @retry
    def actregister(self,user,mail_code,geetest_code_key):
        json_data = {
            "lang": "en-GB",
            "data":
                {
                    "source": "WEB",
                    "email": user,
                    "loginPwd": t.md5Pass(t.create_pwd()),
                    "emailCode": mail_code,
                    "geetestKey": geetest_code_key,
                    "activityCode": "PRL_AIRDROP"
                }
        }
        res=r.post('https://www.coinsuper.com/v1/member/user/actregister',data=json.dumps(json_data),headers=self.header,proxies=self.proxies).json()
        print('最后注册的结果'+res)

    '批注册'
    @retry
    def registers(self, user, mail_code, geetest_code_key):
        pwd=t.create_pwd()
        print('用户名：'+user[0]+'密码:'+user[1])
        print('密码是：'+pwd+'验证码：'+mail_code)
        json_data = {
            "lang": "en-GB",
            "data":
                {
                    "source": "WEB",
                    "email": user[0],
                    "loginPwd": t.md5Pass(pwd),
                    "emailCode": mail_code,
                    "geetestKey": geetest_code_key,
                    "activityCode": "PRL_AIRDROP"
                }
        }

        header = t.getHeaders()
        header['Content - Type'] = "application/json;charset=UTF-8"
        header['X-B3-Traceid'] = "9084308976537210"
        header['XX-B3-Spanid'] = "9084308976537210"
        header['Host'] = "www.coinsuper.com"
        header['X-Requested-With'] = "XMLHttpRequest"
        header['Referer'] = "https://www.coinsuper.com/"
        header['Accept-Language'] = "zh-CN,zh;q=0.8"
        header['Accept'] = "*/*"
        ip=t.getProXY()
        print('使用的代理：%s'%ip)
        try:
            res = r.post('https://www.coinsuper.com/v1/member/user/actregister', proxies={"https":ip}, data=json.dumps(json_data), headers=header,timeout=10)
        except Exception as e:
            print('出错了')
            print(e)
        print('最后注册的结果' +str( res.status_code))

        w=open(t.getPropath()+'/suessce.txt','a+')
        w.write(user[0]+'---'+pwd+'---'+user[1]+'\n')
        w.close()


    '提取验证码'
    def getvrif(self, html, msg):
        try:
            return  html.split(msg)[1].split(' ')[0].strip()
        except:
            return  None

    '异步发送验证码'
    async  def async_send_msg(self,path):
        f = open(path, 'r', encoding='utf-8')
        print('%s' % threading.currentThread())
        for line in f.readlines():
            l = line.strip().replace('\n', '')
            if l == '':
                continue
            l = re.split(config.split_title + '+', l)
            msg_mail = config.cookies_163.get(l[0])
            if msg_mail == None:
                continue
            print('当前账号:' + l[0])
            self.async_send_sms(l, msg_mail)
        f.close()
        os.remove(path)
        print(path+'完成')


    def async_send_sms(self,user,msg_mail):
        v = self.getjiyan_key()
        geetest_key = self.geetest_key(v, user[0])
        if geetest_key==None:
            return False
        sms_msg = self.send_sms(user[0], geetest_key)['msg']
        if sms_msg != 'success':
            print(sms_msg)
            return False
        print('发送验证码成功')
        config.list_job.append([user, self.get_vrif, msg_mail, self.registers, geetest_key,
                                datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')])
        return True